import {DateUtils, ObjUtils} from '../../utils/Utils';
import ToastUtils from '../../common/ToastUtils';

//单个聊天的链接
export default class IMSinglerLinker {
  constructor(props) {
    this.PAGE_SIZE = 10;
    //链接ID
    this._linkerId = -1;
    //链接类型  0 私聊  1群聊
    this._linkerType = props.linkerType;
    //对方的数据
    this._talkerData = props.talkerData;

    this._allDatas = [];//存储所有请求到的数据

    this._dataKey = null;

    this._isSending = false;
    this._requesting = false;
    this._isLoadMore = false;
    this._needSort = true;
    this._params = null;
  }

  getDatas() {
    return this._allDatas;
  }

  init(params) {
    this._isSending = false;
    this._params = params;
    this._updateCall = params.updateCall;
    this._sendMessageCall = params.sendMessageCall;
  }

  dispose() {
    this._allDatas = [];
  }

  sendMessage(message) {
    if(this._isSending === true) {
      return;
    }
    this._isSending = true;
    this._dealSendMessage(message);
  }

  requestData(loadMore) {
    // if(this._requesting === true) {
    //   // ToastUtils.show("正在发送，请稍后...");
    //   return false;
    // }
    this._requesting = true;
    this._isLoadMore = loadMore === true;
    console.log("requestData", loadMore);
    this._dealRequestData();
    return true;
  }

  _dealSendMessage(message) {

  }

  _dealRequestData() {

  }

  requestFinish(datas, result) {
    if(this._dataKey === null) {
      console.error("Error:dataKey can not be null");
    }
    if(result && datas) {
      this._dealDatas(datas);
      this._isLoadMore === true && this._dealLoadMoreSuccess(datas);
    }
    this._sendUpdateCall(result, this._isLoadMore);
    this._requesting = false;
    this._isLoadMore = false;
  }

  _sendUpdateCall(result, isLoadMore) {
    this._updateCall(this._allDatas, result, isLoadMore);
  }

  _dealDatas(datas) {
    this._allDatas = ObjUtils.concatArrayNoRepeat(this._allDatas, datas, this._dataKey + "");
    this._needSort === true && this._allDatas.sort(this._sortData.bind(this));
  }

  _dealLoadMoreSuccess() {

  }

  _sortData(aData, bData) {
    let aDate1 = DateUtils.getDate(aData.sent_at);
    let bDate2 = DateUtils.getDate(bData.sent_at);
    return DateUtils.compareDate(aDate1, bDate2);
  }

  sendMessageFinish(isSucceed, status) {
    this._isSending = false;
    this._sendMessageCall(isSucceed, status);
  }
}
